package cn.mujiankeji.mbrowser.数据.数据库

import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Insert
import androidx.room.Update
import androidx.room.Delete
import androidx.room.Query
import androidx.room.OnConflictStrategy
import kotlinx.coroutines.flow.Flow
import kotlinx.datetime.Clock

@Entity
data class DBBookmark(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,

    @ColumnInfo(name = "is_dir", defaultValue = "0")
    var 是否目录 : Boolean = false, // 是否为文件夹

    @ColumnInfo(name = "title", defaultValue = "")
    var 标题: String = "",

    @ColumnInfo(name = "url", defaultValue = "")
    var 网址: String = "", // 如果是文件夹，此字段可为空或特定值

    @ColumnInfo(name = "icon", defaultValue = "NULL")
    var 图标: String? = null,

    @ColumnInfo(name = "pos", defaultValue = "0")
    var 排序 : Int = 0, // 在同一文件夹中的排序位置

    @ColumnInfo(name = "time_create", defaultValue = "0") // 建议在插入时动态设置当前时间
    val 添加时间: Long = Clock.System.now().toEpochMilliseconds(),

    @ColumnInfo(name = "fid", defaultValue = "0")
    val 文件夹Id: Long = 0L
)

@Dao
interface DaoBookmark{

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun 插入条目(条目: DBBookmark): Long

    @Update
    suspend fun 更新条目(条目: DBBookmark)

    @Delete
    suspend fun 删除条目(条目: DBBookmark)

    @Query("SELECT * FROM DBBookmark WHERE id = :id")
    fun 根据Id获取条目(id: Long): Flow<DBBookmark?>

    @Query("SELECT * FROM DBBookmark WHERE fid = 0 AND is_dir = 0 ORDER BY pos ASC")
    fun 获取顶级书签(): Flow<List<DBBookmark>>

    @Query("SELECT * FROM DBBookmark WHERE fid = 0 AND is_dir = 1 ORDER BY pos ASC")
    fun 获取顶级文件夹(): Flow<List<DBBookmark>>

    @Query("SELECT * FROM DBBookmark WHERE fid = :folderId AND is_dir = 0 ORDER BY pos ASC")
    fun 获取指定文件夹下的书签(folderId: Long): Flow<List<DBBookmark>>

    @Query("SELECT * FROM DBBookmark WHERE fid = :folderId AND is_dir = 1 ORDER BY pos ASC")
    fun 获取指定文件夹下的子文件夹(folderId: Long): Flow<List<DBBookmark>>

    @Query("SELECT * FROM DBBookmark WHERE fid = :folderId ORDER BY pos ASC")
    fun 获取指定文件夹下的所有条目(folderId: Long): Flow<List<DBBookmark>>

    @Query("SELECT * FROM DBBookmark WHERE is_dir = 0 AND (title LIKE '%' || :keyword || '%' OR url LIKE '%' || :keyword || '%') ORDER BY time_create DESC")
    fun 搜索书签(keyword: String): Flow<List<DBBookmark>>

    @Query("SELECT * FROM DBBookmark ORDER BY fid, pos ASC")
    fun 获取所有条目(): Flow<List<DBBookmark>>

    @Query("DELETE FROM DBBookmark")
    suspend fun 清空所有条目()

    // 递归删除文件夹及其所有子项 (书签和子文件夹)
    // 这通常在 Repository 层面实现，因为它涉及到多次数据库查询和删除操作
    // DAO层面可以提供基础的删除方法
    @Query("DELETE FROM DBBookmark WHERE id = :id")
    suspend fun 根据Id删除条目(id: Long)

    @Query("SELECT * FROM DBBookmark WHERE fid = :folderId")
    suspend fun 获取指定文件夹下的所有条目列表Suspend(folderId: Long): List<DBBookmark> // 用于递归删除
}